package br.com.salao.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.salao.bean.Endereco;
import br.com.salao.util.JpaUtil;

public class EnderecoDaoImpl implements EnderecoDao{
	
	private final GenericDao<Endereco> dao;
	
	public EnderecoDaoImpl(EntityManager em){
		dao = new GenericDao<Endereco>(em, Endereco.class);
	}
	
	public Endereco inserir(Endereco endereco){
		return dao.salvar(endereco);		
	}
	
	public Endereco buscarEnderecoPorLogradouro(Endereco endereco){
		
		EntityManager em = JpaUtil.getEntityManager();
		Endereco enderecoBD = null;
		
		try {		
			Query query = em.createQuery("from Endereco e where e.logradouro like :logradouro and e.numero =:numero ");
			query.setParameter("logradouro", endereco.getLogradouro());
			query.setParameter("numero", endereco.getNumero());
			enderecoBD = (Endereco) query.getSingleResult();	
			
		} catch (Exception e) {
			enderecoBD = null;

		}finally{
			if(em != null){
				em.close();
			}
		}
		return enderecoBD;
	}
	
	
	public Endereco buscarEnderecoPorIdEstabelecimento(int idEstabelecimento){
		
		EntityManager em = JpaUtil.getEntityManager();
		Endereco enderecoBD = null;
		
		try {		
			Query query = em.createQuery("from Endereco e where e.estabelecimento.id = :idEstabelecimento");
			query.setParameter("idEstabelecimento", idEstabelecimento);

			enderecoBD = (Endereco) query.getSingleResult();	
			
		} catch (Exception e) {
			
			enderecoBD = null;
			e.printStackTrace();
			
		}finally{
			if(em != null){
				em.close();
			}
		}
		return enderecoBD;
	}
	
	public List<Endereco> buscarEnderecoPorIdBairro(int idBairro){
		
		EntityManager em = JpaUtil.getEntityManager();
		List<Endereco> enderecoBD = null;
		
		try {		
			Query query = em.createQuery("from Endereco e where e.bairro.id = :idBairro ");
			query.setParameter("idBairro", idBairro);

			enderecoBD = (List<Endereco>) query.getResultList();	
			
		} catch (Exception e) {
			enderecoBD = null;
			e.printStackTrace();
		}finally{
			if(em != null){
				em.close();
			}
		}
		return enderecoBD;
	}	
}
